import { Component, OnInit } from '@angular/core'
import { Router } from '@angular/router'
import { Location } from '@angular/common'
import { MineService } from '../index/services/mine.service'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'
import { CoolSessionStorage } from 'src/app/common/coolStorage/cool-session-storage'
import { ActionSheet } from 'ng-zorro-antd-mobile'
import { environment } from 'src/environments/environment.prod'
import { HttpClientService } from 'src/app/common/httpClient/http'

declare var navigator: any
declare var Camera: any
declare var FileTransfer: any
declare var FileUploadOptions: any

@Component({
  selector: 'app-person-info',
  templateUrl: './person-info.component.html',
  styleUrls: ['./person-info.component.scss'],
  providers: [ActionSheet]
})
export class PersonInfoComponent implements OnInit {
  userinfo: any
  error = false
  loading = false

  constructor(
    private router: Router,
    private location: Location,
    private service: MineService,
    private utils: CommonUtil,
    private storage: CoolLocalStorage,
    private session: CoolSessionStorage,
    private actionSheet: ActionSheet,
    private http: HttpClientService
  ) {}

  // 初始化
  ngOnInit() {
    this.getCurrentUser()
  }
  // 返回
  onClickLeft() {
    this.location.back()
  }
  // 获取个人资料
  getCurrentUser() {
    this.loading = true
    this.service.getCurrentUser(
      res => {
        setTimeout(() => {
          this.error = false
          this.loading = false
        }, 500)
        if (res.Success && res.Result) {
          let Photo = 'assets/images/House/profile_user_info_photo.png'
          if (res.Result.Photo) {
            Photo = JSON.parse(res.Result.Photo)[0].Items[0]
          }
          res.Result.Photo = Photo
          this.userinfo = res.Result
          this.session.removeItem('personModify')
          this.storage.setObject('userinfo', res.Result)
        }
      },
      () => {
        setTimeout(() => {
          this.error = true
          this.loading = false
        }, 500)
      }
    )
  }
  // 设置头像
  setAvatarAction(message) {
    let BUTTONS = ['拍照', '从相册选取', '取消']
    ActionSheet.showActionSheetWithOptions(
      {
        options: BUTTONS,
        cancelButtonIndex: BUTTONS.length - 1,
        message: message,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex === 0) {
          this.takePhoto()
        } else if (buttonIndex === 1) {
          this.selectFromAlbum()
        }
      }
    )
  }
  // 头像上传至服务器
  setAvatarRequest(url) {
    let photo = [
      {
        Index: 0,
        Items: [url]
      }
    ]
    let reqdata = {
      birthday: null,
      certificateId: null,
      certificateType: null,
      name: null,
      nick: null,
      photo: JSON.stringify(photo),
      sex: null
    }
    this.http.post(
      reqdata,
      '/Platform/Json/UserService.svc/Complete',
      res => {
        this.userinfo.Photo = url
        this.session.setItem('personModify', 'true')
        this.utils.hide()
        this.utils.info('头像已更换')
      },
      error => {
        this.utils.hide()
        this.utils.info('头像上传失败，请重试')
        console.log(error)
      }
    )
  }
  // 拍照
  takePhoto() {
    let options = {
      quality: 50,
      destinationType: Camera.DestinationType.FILE_URI,
      encodingType: Camera.EncodingType.PNG,
      mediaType: Camera.MediaType.PICTURE,
      sourceType: Camera.PictureSourceType.CAMERA,
      allowEdit: true,
      targetWidth: 320,
      targetHeight: 320,
      cameraDirection: Camera.Direction.FRONT
    }
    navigator.camera.getPicture(
      res => {
        this.onSuccess(res)
      },
      error => {
        this.onError(error)
      },
      options
    )
  }
  // 从相册选择
  selectFromAlbum() {
    let options = {
      destinationType: Camera.DestinationType.FILE_URI,
      encodingType: Camera.EncodingType.PNG,
      mediaType: Camera.MediaType.PICTURE,
      sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
      allowEdit: true,
      targetWidth: 320,
      targetHeight: 320
    }
    navigator.camera.getPicture(
      res => {
        this.onSuccess(res)
      },
      error => {
        this.onError(error)
      },
      options
    )
  }
  // 成功
  onSuccess(res) {
    this.utils.loading('正在上传...')
    let options = new FileUploadOptions()
    let ft = new FileTransfer()
    let url = environment.baseUrl + '/House1/Upload.ashx?target=FileUserDirectory'
    options.fileKey = 'file'
    ft.upload(
      res,
      encodeURI(url),
      success => {
        let imgUrl = success.response
        this.setAvatarRequest(imgUrl)
      },
      error => {
        this.utils.hide()
        this.utils.info('图片上传失败，请重试')
        console.log(error)
      },
      options
    )
  }
  // 失败
  onError(err) {
    console.log(err)
  }
  // 修改个人资料
  handleModify(type) {
    // 前往二维码页面
    if (type === 'qrcode') {
      this.router.navigate([
        '/workspace/mine/qrcode',
        { Nick: this.userinfo['Nick'], Captcha: this.userinfo['Captcha'] }
      ])
    } else {
      this.router.navigate(['/workspace/mine/personModify', { type: type, value: this.userinfo[type] || '' }])
    }
  }
  // 刷新
  handleReload() {
    this.error = false
    this.loading = true
    this.getCurrentUser()
  }
}
